const jwt = require("jsonwebtoken");
const tokenList = require("./token.json");
const key = "jwt2023";
const ignoreList = ["/admin/acl/index/login", "/admin/acl/index/logout"];

const sign = (data = {}) => {
  return jwt.sign(data, key, { expiresIn: "1d", algorithm: "HS256" });
};
// 验证token
const verify = (req, res, next) => {
  // console.log(req.url);

  // 免验证
  if (ignoreList.includes(req.url)) return next();

  let authorization =
    req.headers.authorization || req.body.token || req.query.token || "";
  let token = "";
  if (authorization.includes("Bearer")) {
    token = authorization.replace("Bearer ", "");
  } else {
    token = authorization;
  }
  // console.log(token);

  if (tokenList.includes(token)) {
    // 如果token在黑名单 直接返回
    return res.send({
      code: 10011,
      message: "无效的token",
      ok: true,
    });
  }
  jwt.verify(token, key, (err, data) => {
    // console.log(error, data);
    if (err) {
      if (err.name == "TokenExpiredError") {
        //token过期
        return res.send({
          code: 10010,
          message: "token过期",
          ok: true,
        });
      } else if (err.name == "JsonWebTokenError") {
        //无效的token
        return res.send({
          code: 10011,
          message: "无效的token",
          ok: true,
        });
      }
    } else {
      req._id = data.id;
      next();
    }
  });
};

module.exports = {
  sign,
  verify,
  key,
};
